package com.atguigu.IO;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 例题2:客户端发送信息给服务端，服务端将文件保存在本地
 */
public class TCPTest2 {
    //
    @Test
    public void client() throws IOException {
        Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9090);
        OutputStream outputStream = socket.getOutputStream();
        FileInputStream fis=new FileInputStream(new File("hello.txt"));
        byte[] buffer=new byte[1024];
        int len;
        while((len=fis.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }
        fis.close();
        outputStream.close();
        socket.close();
    }

    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(9090);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos=new FileOutputStream(new File("hhh"));
        byte[] buffer=new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
